/**
 * Created by 德予 on 2015/12/15. copyright(c)
 */
cimsTech.controller('mainCtl', ['$scope', 'sWSocket', '$location', function($scope, sWSocket, $location) {
    $scope.activePage = function(path) {
        return path === $location.path();
    };
}]).controller('ModalInstanceCtrl', ['$scope', '$uibModalInstance', 'errorMsg', function($scope, $uibModalInstance, errorMsg) {
    $scope.errorMsg = errorMsg;
    $scope.ok = function() {
        $uibModalInstance.close();
    };
}]).controller('modelCtl', ['$scope', '$rootScope', 'ConnList', 'SCADA', function($scope, $rootScope, ConnList, SCADA) {
    // angular.element('.value-tab').addClass('value-tab-in');
    $scope.connectPool = ConnList.getConnectList();
    $scope.refreshNode = function() {
        $scope.$broadcast('reAsyncChildNodes');
    };
    $scope.$watch('activeConn', function(n) {
        if($scope.connectPool[n].isConnect === 'connected') {
            $scope.$broadcast('initTree', $scope.connectPool[$rootScope.activeConn].ip);
        } else {
            $scope.$broadcast('destroyTree');
        }
        // $scope.valueList = SCADA.getValueList();
        $scope.gridOptions.data = SCADA.getValueList();
    });
    // $scope.valueList = SCADA.getValueList();
    $scope.gridOptions = {
        columnDefs: [{
            field: 'key',
            displayName: '\u91cf\u6d4b\u540d\u79f0',
            width: '40%'
        }, {
            field: 'v',
            displayName: '\u91cf\u6d4b\u503c'
        }, {
            field: 't',
            displayName: '\u4e0a\u9001\u65f6\u95f4'
        }, {
            field: 'q',
            displayName: '\u8d28\u91cf\u7801'
        }],
        data: SCADA.getValueList(),
        multiSelect: true,
        i18n: 'zh-cn'
    };
}]).controller('reportCtl', ['$scope', '$rootScope', 'sWSocket', 'ConnList', 'ReportService', function($scope, $rootScope, sWSocket, ConnList, ReportService) {
    $scope.connectPool = ConnList.getConnectList();
    $scope.reportPool = {};
    $scope.reportSwitch = $scope.connectPool[$rootScope.activeConn].reportStatus;
    $scope.isDisable = false;
    sWSocket.addCallback('update', function(data) {
        $scope.reportPool[data.ip] = $scope.reportPool[data.ip] || [];
        $scope.$apply(function($scope) {
            if(!$scope.reportPool[data.ip] || $scope.reportPool[data.ip].length < 1) {
                $scope.reportPool[data.ip] = $scope.reportPool[data.ip].concat(data.update.values);
            } else {
                for(var i = 0; i < data.update.values.length; i++) {
                    var flag = false;
                    for(var j = 0; j < $scope.reportPool[data.ip].length; j++) {
                        flag |= $scope.reportPool[data.ip][j].key === data.update.values[i].key;
                        if(flag) {
                            $scope.reportPool[data.ip][j] = data.update.values[i];
                            break;
                        }
                    }
                    if(!flag) {
                        $scope.reportPool[data.ip].push(data.update.values[i]);
                    }
                }
            }
        });
    });
    $scope.switchReport = function() {
        $scope.isDisable = true;
        ReportService.switchReport({
            url: $scope.connectPool[$rootScope.activeConn].ip,
            _switch: $scope.reportSwitch ? 'Disable' : 'Enable'
        }).then(function() {
            $scope.reportSwitch = !$scope.reportSwitch;
            $scope.isDisable = false;
        }, function() {
            $scope.connectPool[$rootScope.activeConn].reportStatus = false;
            $scope.isDisable = false;
        });
    };
    $scope.$watch('activeConn', function(n) {
        $scope.reportSwitch = $scope.connectPool[n].reportStatus;
        if(!$scope.reportPool[$scope.connectPool[n].ip]) {
            $scope.reportPool[$scope.connectPool[n].ip] = [];
        }
    });
    $scope.gridOptions = {
        columnDefs: [{
            field: 'key',
            displayName: '\u91cf\u6d4b\u540d\u79f0',
            width: '40%'
        }, {
            field: 'v',
            displayName: '\u91cf\u6d4b\u503c'
        }, {
            field: 't',
            displayName: '\u4e0a\u9001\u65f6\u95f4'
        }, {
            field: 'q',
            displayName: '\u8d28\u91cf\u7801'
        }],
        data: 'reportPool[connectPool[activeConn].ip]',
        multiSelect: true,
        i18n: 'zh-cn'
    };
}]).controller('fileserverCtl', ['$scope', '$rootScope', 'fileService', '$uibModal', 'ProgressBar', '$localStorage', function($scope, $rootScope, fileList, $uibModal, ProgressBar, $localStorage) {
    $scope.fileItems = fileList.getFileList();
    $scope.selectedItems = [];
    $localStorage.radioModel = $localStorage.radioModel || 'view-icons';
    $scope.radioModel = $localStorage.radioModel;
    $scope.back = {name: '\\', id: '', path: '\\'};
    $scope.progressBar = new ProgressBar();
    var goBackPathMatch = new RegExp(/[^\\]*\\$/);
    $scope.selectItem = function(item, e) {
        e.stopPropagation();
        item.selected = !item.selected;
        if(item.selected) {
            $scope.selectedItems.push(item);
        } else {
            $scope.selectedItems.remove(item);
        }
    };
    $scope.$on('expandNode', function(e, d) {
        $scope.back = {name: d.title.replace('\\', ''), id: d.fullPath, path: d.id};
    });
    $scope.itemOnClick = function(item, e) {
        if(!item.isParent) {
            var url = window.location.origin + window.location.pathname + 'rest/getFile/' + item.name + '?url=' + $scope.connectPool[$rootScope.activeConn].ip + '&id=' + item.id;
            var elemIF = document.createElement('iframe');
            elemIF.src = url;
            elemIF.style.display = 'none';
            document.body.appendChild(elemIF);
        } else {
            $scope.progressBar.show();
            fileList.readDir(item, $scope.connectPool[$rootScope.activeConn].ip).then(function(data) {
                $scope.back = {name: item.name, id: item.fullPath, path: item.id};
                $scope.fileItems = data;
                $scope.progressBar.hide();
            }, function() {
                $scope.back = {name: item.name, id: item.fullPath, path: item.id};
                $scope.fileItems.length = 0;
                $scope.progressBar.hide();
            });
        }
        e.stopPropagation();
    };
    $scope.goBack = function(e) {
        $scope.progressBar.show();
        fileList.readDir($scope.back, $scope.connectPool[$rootScope.activeConn].ip).then(function(data) {
            $scope.fileItems = data;
            var id = $scope.back.id.replace(goBackPathMatch, '');
            var path = $scope.back.path.replace(goBackPathMatch, '');
            var name = $scope.back.id.match(goBackPathMatch);
            $scope.back = {name: name[0] ? name[0].replace('\\', '') : '\\', id: id, path: path};
            $scope.progressBar.hide();
        }, function() {
            $scope.fileItems.length = 0;
            $scope.progressBar.hide();
        });
        e.stopPropagation();
    };
    $scope.multDelete = function() {
        if($scope.selectedItems.length > 0) {
            $scope.progressBar.show();
            fileList.removeFile($scope.connectPool[$rootScope.activeConn].ip, $scope.selectedItems).then(function() {
                fileList.readDir({
                    id: $scope.back.path
                }, $scope.connectPool[$rootScope.activeConn].ip).then(function(data) {
                    $scope.fileItems = data;
                    $scope.progressBar.hide();
                }, function() {
                    $scope.fileItems.length = 0;
                    $scope.progressBar.hide();
                });
            }, function() {
                $scope.progressBar.hide();
            });
        }
    };
    $scope.clearSelected = function() {
        angular.forEach($scope.fileItems, function(item) {
            item.selected = false;
        });
        $scope.selectedItems.length = 0;
    };
    $scope.upload = function() {
        var modalInstance = $uibModal.open({
            templateUrl: 'fileUploader.html',
            controller: 'filesUploadCtl',
            size: 'lg',
            backdrop: 'static',
            resolve: {
                back: function() {
                    return $scope.back;
                }
            }
        });
        modalInstance.result.then(function() {
            $scope.progressBar.show();
            fileList.readDir({id: $scope.back.path}, $scope.connectPool[$rootScope.activeConn].ip).then(function(data) {
                $scope.fileItems = data;
                $scope.progressBar.hide();
            }, function() {
                $scope.fileItems.length = 0;
                $scope.progressBar.hide();
            });
        });
    };
    $scope.$watch('activeConn', function(n) {
        if($scope.connectPool[n].isConnect === 'connected') {
            $scope.$broadcast('initTree', $scope.connectPool[$rootScope.activeConn].ip);
        } else {
            $scope.$broadcast('destroyTree');
        }
        $scope.fileItems.length = 0;
        $scope.back = {};
    });
    $scope.$watch('radioModel', function(n, o) {
        angular.element('#view').removeClass(o).addClass(n);
    });
}]).controller('settingsCtl', ['$scope', '$http', function($scope, $http) {
    $scope.Submit = function() {
        $http.post('rest/setting', {
            connectTimeOut: $scope.connectTimeOut,
            filedirTimeOut: $scope.filedirTimeOut
        });
    };
}]).controller('filesUploadCtl', ['$scope', '$rootScope', 'ConnList', 'back', 'FileUploader', '$uibModalInstance', function($scope, $rootScope, ConnList, back, FileUploader, $uibModalInstance) {
    $scope.connectPool = ConnList.getConnectList();
    $scope.showCancel = false;
    var uploader = $scope.uploader = new FileUploader({
        url: 'rest/upload'
    });
    $scope.cancel = function() {
        $uibModalInstance.close();
    };
    uploader.onBeforeUploadItem = function(item) {
        var param = {
            url: $scope.connectPool[$rootScope.activeConn].ip,
            path: back.path
        };
        item.formData.push(param);
    };
    uploader.onErrorItem = function(fileItem, response, status, headers) {
    };
}]);
cimsTech.filter('lastModified', function() {
    return function(input) {
        var yyyy = input.substr(0, 4),
            MM = input.substr(4, 2),
            dd = input.substr(6, 2),
            hh = input.substr(8, 2),
            mm = input.substr(10, 2),
            ss = input.substr(12, 2);
        return yyyy + '-' + MM + '-' + dd + '\n' + hh + ':' + mm + ':' + ss;
    };
}).filter('fileSize', function() {
    return function(input) {
        var size = parseInt(input);
        if(isNaN(size)) {
            return input;
        } else {
            if(size < 1024) {
                return size + 'B';
            } else if(size / 1024 < 1024) {
                return (size / 1024).toFixed(2) + 'KB';
            } else {
                return (size / 1024 / 1024).toFixed(2) + 'MB';
            }
        }
    };
});